package sentinel

import (
	"fmt"
	"gc-rds-ha/internal/common"

	log "github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type MysqlParams struct {
	User               string
	Pwd                string
	Host               string
	Port               uint32
	MasterLogFile      string
	ReadMasterLogPos   string
	RelayMasterLogFile string
	ExecMasterLogPos   string
	DB                 *gorm.DB
}

func (m *MysqlParams) OpenMysql() (*gorm.DB, error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/?charset=utf8mb4&parseTime=True&loc=Local&timeout=3s",
		m.User,
		m.Pwd,
		m.Host,
		m.Port,
	)
	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN: dsn,
	}), &gorm.Config{})
	if err != nil {
		log.WithField("error:", log.Fields{
			"mysql": dsn,
			"error": err,
		}).Error("connect mysql failed!")
		return db, err
	}

	if common.AgentConfig.Debug {
		db = db.Debug()
	}
	return db, nil
}
